import 'dart:io';
import 'dart:math';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';

import '../../common/index.dart';
import 'index.dart';

class AddPlantPage extends GetView<AddPlantController> {
  const AddPlantPage({super.key});

  // 主视图
  Widget _buildView(BuildContext context) {
    return Column(
      children: [
        SizedBox(height: 45.h),
        Row(
          children: [
            SizedBox(width: 24.w),
            // 返回按钮添加动画效果
            TweenAnimationBuilder<double>(
              duration: const Duration(milliseconds: 300),
              tween: Tween<double>(begin: 0, end: 1),
              builder: (context, value, child) {
                return Transform.translate(
                  offset: Offset((1 - value) * 20, 0),
                  child: Opacity(opacity: value, child: child),
                );
              },
              child: MouseRegion(
                cursor: SystemMouseCursors.click,
                onEnter: (_) => controller.set_back_button_scale(1.1),
                onExit: (_) => controller.set_back_button_scale(1.0),
                child: Obx(
                  () => AnimatedScale(
                    duration: Duration(milliseconds: 150),
                    scale: controller.back_button_scale.value,
                    child: GestureDetector(
                      onTap: () {
                        // 点击时的缩放效果
                        HapticFeedback.selectionClick();
                        final FocusScopeNode currentFocus = FocusScope.of(
                          context,
                        );
                        if (!currentFocus.hasPrimaryFocus) {
                          currentFocus.unfocus();
                        }
                        RouteUtil.pop();
                      },
                      child: Container(
                        width: 40.w,
                        height: 40.h,
                        decoration: BoxDecoration(
                          color: Colors.black,
                          borderRadius: BorderRadius.circular(10.r),
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black.withOpacity(0.3),
                              offset: Offset(0, 2),
                              blurRadius: 5,
                            ),
                          ],
                        ),
                        child: Center(
                          child: SvgPicture.asset(
                            AssetsImages.back,
                            width: 20.w,
                            height: 20.h,
                            color: Color(0xFFCDFF5F),
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ),
            Spacer(),
          ],
        ),
        SizedBox(height: 35.h),
        // 植物图标添加脉动动画
        Obx(
          () => GestureDetector(
            onTap: () {
              HapticFeedback.mediumImpact();
              controller.set_plant_icon_scale(0.9);
              Future.delayed(Duration(milliseconds: 100), () {
                controller.set_plant_icon_scale(1.0);
                controller.pick_image();
              });
            },
            child: AnimatedScale(
              duration: Duration(milliseconds: 200),
              scale: controller.plant_icon_scale.value,
              child: TweenAnimationBuilder<double>(
                duration: const Duration(milliseconds: 2000),
                tween: Tween<double>(begin: 0.95, end: 1.0),
                curve: Curves.elasticOut,
                builder: (context, value, child) {
                  return Transform.scale(scale: value, child: child);
                },
                child: Stack(
                  children: [
                    Container(
                      width: 100.w,
                      height: 100.h,
                      decoration: BoxDecoration(
                        color: Colors.black,
                        shape: BoxShape.circle,
                        boxShadow: [
                          BoxShadow(
                            color: Color(0xFFCDFF5F).withOpacity(0.3),
                            blurRadius: 10,
                            spreadRadius: 2,
                          ),
                        ],
                      ),
                      child: controller.selected_image.value == null
                          ? Center(
                              child: AnimatedRotation(
                                duration: Duration(milliseconds: 500),
                                turns: controller.rotation_value.value,
                                child: Image.asset(
                                  AssetsImages.addPlant,
                                  width: 80.w,
                                  height: 80.h,
                                  fit: BoxFit.contain,
                                ),
                              ),
                            )
                          : Hero(
                              tag: 'selected_plant_image',
                              child: ClipOval(
                                child: Image.file(
                                  File(controller.selected_image.value!.path),
                                  width: 100.w,
                                  height: 100.h,
                                  fit: BoxFit.cover,
                                ),
                              ),
                            ),
                    ),
                    Positioned(
                      right: 0,
                      bottom: 0,
                      child: AnimatedContainer(
                        duration: Duration(milliseconds: 300),
                        width: 30.w,
                        height: 30.h,
                        decoration: BoxDecoration(
                          color: Colors.white,
                          shape: BoxShape.circle,
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black.withOpacity(0.2),
                              blurRadius: 4,
                              spreadRadius: 1,
                            ),
                          ],
                        ),
                        child: TweenAnimationBuilder<double>(
                          duration: Duration(milliseconds: 1000),
                          tween: Tween<double>(begin: 0, end: 1),
                          builder: (context, value, child) {
                            return Transform.rotate(
                              angle: value * 0.2,
                              child: child,
                            );
                          },
                          child: SvgPicture.asset(
                            AssetsImages.addPlantSvg,
                            width: 30.w,
                            height: 30.h,
                          ),
                        ),
                      ),
                    ),
                    if (controller.is_loading.value)
                      Positioned.fill(
                        child: Container(
                          decoration: BoxDecoration(
                            color: Colors.black.withOpacity(0.7),
                            shape: BoxShape.circle,
                          ),
                          child: Center(
                            child: CircularProgressIndicator(
                              color: Color(0xFFCDFF5F),
                            ),
                          ),
                        ),
                      ),
                  ],
                ),
              ),
            ),
          ),
        ),
        SizedBox(height: 40.h),
        // 名称标签和输入
        TweenAnimationBuilder<double>(
          duration: const Duration(milliseconds: 800),
          tween: Tween<double>(begin: 0, end: 1),
          builder: (context, value, child) {
            return Opacity(
              opacity: value,
              child: Transform.translate(
                offset: Offset(0, (1 - value) * 20),
                child: child,
              ),
            );
          },
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 24.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                ShakeAnimationWidget(
                  shakeAnimationController:
                      controller.name_error_shake_controller,
                  shakeOffset: 10,
                  child: Text(
                    'Name',
                    style: TextStyle(
                      fontSize: 16.sp,
                      fontWeight: FontWeight.w600,
                      color: Colors.black,
                    ),
                  ),
                ),
                SizedBox(height: 8.h),
                ShakeAnimationWidget(
                  shakeAnimationController:
                      controller.name_error_shake_controller,
                  shakeOffset: 10,
                  child: Container(
                    width: 340.w,
                    decoration: BoxDecoration(
                      color: Colors.black,
                      borderRadius: BorderRadius.circular(10.r),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.1),
                          offset: Offset(0, 3),
                          blurRadius: 6,
                        ),
                      ],
                    ),
                    child: Obx(
                      () => AnimatedContainer(
                        duration: Duration(milliseconds: 200),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(10.r),
                          border: Border.all(
                            color: controller.is_focused.value
                                ? Color(0xFFCDFF5F)
                                : Colors.transparent,
                            width: 2,
                          ),
                        ),
                        child: TextField(
                          controller: controller.name_controller,
                          style: TextStyle(
                            color: Color.fromRGBO(255, 255, 255, 0.84),
                          ),
                          decoration: InputDecoration(
                            hintText: 'Input Name',
                            hintStyle: TextStyle(
                              fontSize: 12.sp,
                              fontWeight: FontWeight.w400,
                              color: Colors.grey,
                            ),
                            contentPadding: EdgeInsets.symmetric(
                              horizontal: 16.w,
                            ),
                            border: InputBorder.none,
                          ),
                          onTap: () {
                            // 输入框获得焦点时的动画
                            HapticFeedback.selectionClick();
                            controller.set_is_focused(true);
                          },
                          onChanged: (text) {
                            // 输入变化时触发控制器更新
                            controller.update();
                          },
                          onSubmitted: (_) {
                            controller.set_is_focused(false);
                          },
                          onEditingComplete: () {
                            controller.set_is_focused(false);
                          },
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),

        SizedBox(height: 225),

        // 保存按钮添加动画效果
        TweenAnimationBuilder<double>(
          duration: const Duration(milliseconds: 1000),
          tween: Tween<double>(begin: 0, end: 1),
          builder: (context, value, child) {
            return Transform.scale(scale: value, child: child);
          },
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 24.w),
            child: Container(
              width: 340.w,
              height: 55.h,
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [Color(0xFFFEED01), Color(0xFFB3A1FE)],
                  begin: Alignment.centerLeft,
                  end: Alignment.centerRight,
                  stops: [0.0302, 0.9569],
                ),
                borderRadius: BorderRadius.circular(30.r),
                boxShadow: [
                  BoxShadow(
                    color: Color.fromRGBO(194, 197, 239, 0.62),
                    offset: Offset(0, 4),
                    blurRadius: 5.3,
                  ),
                ],
              ),
              child: MouseRegion(
                cursor: SystemMouseCursors.click,
                onEnter: (_) => controller.set_save_button_scale(1.05),
                onExit: (_) => controller.set_save_button_scale(1.0),
                child: Obx(
                  () => AnimatedScale(
                    duration: Duration(milliseconds: 150),
                    scale: controller.save_button_scale.value,
                    child: ElevatedButton(
                      onPressed: () {
                        // 添加按钮点击效果
                        HapticFeedback.mediumImpact();
                        final FocusScopeNode currentFocus = FocusScope.of(
                          context,
                        );
                        if (!currentFocus.hasPrimaryFocus) {
                          currentFocus.unfocus();
                        }
                        controller.set_save_button_scale(0.95);
                        Future.delayed(Duration(milliseconds: 100), () {
                          controller.set_save_button_scale(1.0);
                          if (controller.name_controller.text.isEmpty) {
                            controller.trigger_name_error_shake();
                          } else {
                            controller.on_save_tap();
                          }
                        });
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.transparent,
                        shadowColor: Colors.transparent,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(30.r),
                        ),
                        padding: EdgeInsets.zero,
                      ),
                      child: Text(
                        'Save',
                        style: TextStyle(
                          fontSize: 16.sp,
                          fontWeight: FontWeight.w500,
                          color: Colors.white,
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ),
        ),
        Spacer(),
        SizedBox(height: 40.h),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<AddPlantController>(
      init: AddPlantController(),
      id: "add_plant",
      builder: (_) {
        return GestureDetector(
          // 点击空白处关闭键盘
          onTap: () {
            FocusScope.of(context).unfocus();
            controller.set_is_focused(false);
          },
          child: Scaffold(
            resizeToAvoidBottomInset: false,
            body: Container(
              width: double.infinity,
              height: double.infinity,
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage(AssetsImages.addPlantBg),
                  fit: BoxFit.cover,
                ),
              ),
              child: SafeArea(
                top: false,
                bottom: false,
                child: _buildView(context),
              ),
            ),
          ),
        );
      },
    );
  }
}

// 抖动动画小部件
class ShakeAnimationWidget extends StatefulWidget {
  final Widget child;
  final RxBool shakeAnimationController;
  final double shakeOffset;

  const ShakeAnimationWidget({
    Key? key,
    required this.child,
    required this.shakeAnimationController,
    this.shakeOffset = 5.0,
  }) : super(key: key);

  @override
  _ShakeAnimationWidgetState createState() => _ShakeAnimationWidgetState();
}

class _ShakeAnimationWidgetState extends State<ShakeAnimationWidget>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _animation;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 500),
    );
    _animation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _animationController, curve: Curves.elasticIn),
    );

    ever(widget.shakeAnimationController, (bool shouldShake) {
      if (shouldShake) {
        _animationController.forward(from: 0.0);
        Future.delayed(Duration(milliseconds: 500), () {
          widget.shakeAnimationController.value = false;
        });
      }
    });
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _animation,
      builder: (context, child) {
        double offsetX = sin(_animation.value * 3 * 3.14) * widget.shakeOffset;
        return Transform.translate(offset: Offset(offsetX, 0.0), child: child);
      },
      child: widget.child,
    );
  }
}
